<template>
    <div class="upload">
        <el-upload class="avatar-uploader" :action=" basePath + 'ossservice/upload/uploadfile'" :http-request="upload" name="file" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
    </div>
</template>

<script>
import api from '@/api/upload.js';
export default {
    props:['imagePath'],
    data() {
        return {
            imageUrl: '',
            basePath: process.env.VUE_APP_API_URL,
        };
    },
    watch:{
        imagePath(val){
            if(val == '' || val == null){
                this.imageUrl = null
            }
        }
    },
    methods: {
        upload(e) {
            const file = e.file

            const formData = new FormData()

            formData.append('file', file)
            
            this.$axios.post(api.UPLOAD, formData,
            {
                'Content-type': 'multipart/form-data'
            })
            .then(res => {
                if(res.code == 200){
                    this.$emit('setImagePath', res.data.url)
                    
                    //如果上传成功了，那么就将图片显示出来
                    const reader = new FileReader()

                    reader.readAsDataURL(file)
                    reader.onload = () => {
                        this.imageUrl = reader.result
                    }

                }else{
                    this.$error(res.message)
                }
            })
        },
        handleAvatarSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt10M = file.size / 1024 / 1024 < 10;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt10M) {
                this.$message.error('上传头像图片大小不能超过 10MB!');
            }
            return isJPG && isLt10M;
        }
    }
}
</script>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}</style>
